package com.ehsunbehravesh.varzesh3.net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Observable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class NewspaperFetch extends Observable
        implements Runnable {

  private static final String SITE = "http://www.varzesh3.com";

  public void run() {
    try {
      ArrayList result = new ArrayList();
      Document doc = getDocument("http://www.varzesh3.com");
      doc.normalise();
      Elements divs = doc.select("#showImage");
      if ((divs != null) && (divs.size() > 0)) {
        Element div = divs.get(0);
        Elements uls = div.select("ul.ppt");
        if ((uls != null) && (uls.size() > 0)) {
          Element ul = uls.get(0);
          Elements lis = ul.select("li");
          if ((lis != null) && (lis.size() > 0)) {
            for (int i = 0; i < lis.size(); i++) {
              Element li = lis.get(i);
              Elements links = li.select("a");
              Elements ps = li.select("p");
              if ((links != null) && (links.size() > 0)) {
                Element link = links.get(0);
                String href = link.attr("href");
                Document docImage = getDocument("http://www.varzesh3.com" + href);
                divs = docImage.select("div#anc-op");
                String img = "";
                if ((divs != null) && (divs.size() > 0)) {
                  div = divs.get(0);
                  Elements imgs = div.select("img");
                  if ((imgs != null) && (imgs.size() > 0)) {
                    Element elmImg = imgs.get(0);
                    img = elmImg.attr("src");
                  }
                }
                if ((ps != null) && (ps.size() > 0)) {
                  Element p = ps.get(0);
                  String title = p.text();

                  Newspaper newspaper = new Newspaper(title, img);
                  result.add(newspaper);
                  Thread t = new Thread(newspaper);
                  t.start();
                }
              }
            }
          }
        }
      }

      setChanged();
      notifyObservers(result);
    } catch (Exception ex) {
      setChanged();
      notifyObservers(ex);
    }
  }

  private Document getDocument(String url) {
    Document doc = null;
    while (doc == null) {
      try {
        doc = Jsoup.connect(url).get();
      } catch (IOException ex) {
        System.out.println(ex.getMessage());
      }
    }

    return doc;
  }
}